﻿using CCSFeederCameraUI2.Data;
using CCSFeederCameraUI2.Data.MClass;
using CCSFeederCameraUI2.Data.Extensions;
using CCSFeederCameraUI2.Models;
using NLog;
using Prism.Commands;
using Prism.Ioc;
using Prism.Services.Dialogs;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using CCSFeederCameraUI2.Data.ViewModels;
using System.Threading.Tasks;

namespace CCSFeederCameraUI2.ViewModels.Dialogs
{
    public class ParameterDialogViewModel : DialogViewModel
    {
        #region 变量
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private string partNum = string.Empty;
        bool isChanged = false;
        #endregion
        #region 属性
        private string leftCameraIP;
        public string LeftCameraIP
        {
            get { return leftCameraIP; }
            set { SetProperty(ref leftCameraIP, value); }
        }
        private string rightCameraIP;
        public string RightCameraIP
        {
            get { return rightCameraIP; }
            set { SetProperty(ref rightCameraIP, value); }
        }
        private string listenerIp;
        public string ListenerIp
        {
            get { return listenerIp; }
            set { SetProperty(ref listenerIp, value); }
        }
        private string pLCIp;
        public string PLCIp
        {
            get { return pLCIp; }
            set { SetProperty(ref pLCIp, value); }
        }
        private string imagePath;
        public string ImagePath
        {
            get { return imagePath; }
            set { SetProperty(ref imagePath, value); }
        }
        private string scanCOM;
        public string ScanCOM
        {
            get { return scanCOM; }
            set { SetProperty(ref scanCOM, value); }
        }
        private int barLimit;
        public int BarLimit
        {
            get { return barLimit; }
            set { SetProperty(ref barLimit, value); }
        }
        private bool isUseMES;
        public bool IsUseMES
        {
            get { return isUseMES; }
            set { SetProperty(ref isUseMES, value); }
        }
        private string eepeatBarcode;
        public string RepeatBarcode
        {
            get { return eepeatBarcode; }
            set { SetProperty(ref eepeatBarcode, value); }
        }
        private bool isRepeatBarcode;
        public bool IsRepeatBarcode
        {
            get { return isRepeatBarcode; }
            set { SetProperty(ref isRepeatBarcode, value); }
        }
        #endregion
        #region 命令
        private DelegateCommand<object> textBoxLostFocusCommand;
        public DelegateCommand<object> TextBoxLostFocusCommand =>
            textBoxLostFocusCommand ?? (textBoxLostFocusCommand = new DelegateCommand<object>(ExecuteTextBoxLostFocusCommand));
        private DelegateCommand openDirectoryCommand;
        public DelegateCommand OpenDirectoryCommand =>
            openDirectoryCommand ?? (openDirectoryCommand = new DelegateCommand(ExecuteOpenDirectoryCommand));
        private DelegateCommand<object> leftCameraCheckBoxCommand;
        public DelegateCommand<object> LeftCameraCheckBoxCommand =>
            leftCameraCheckBoxCommand ?? (leftCameraCheckBoxCommand = new DelegateCommand<object>(ExecuteLeftCameraCheckBoxCommand));
        private DelegateCommand<object> rightCameraCheckBoxCommand;
        public DelegateCommand<object> RightCameraCheckBoxCommand =>
            rightCameraCheckBoxCommand ?? (rightCameraCheckBoxCommand = new DelegateCommand<object>(ExecuteRightCameraCheckBoxCommand));
        private DelegateCommand<object> useMESCheckBoxCommand;
        public DelegateCommand<object> UseMESCheckBoxCommand =>
            useMESCheckBoxCommand ?? (useMESCheckBoxCommand = new DelegateCommand<object>(ExecuteUseMESCheckBoxCommand));
        private DelegateCommand<object> repeatBarcodeCheckBoxCommand;
        public DelegateCommand<object> RepeatBarcodeCheckBoxCommand =>
            repeatBarcodeCheckBoxCommand ?? (repeatBarcodeCheckBoxCommand = new DelegateCommand<object>(ExecuteRepeatBarcodeCheckBoxCommand));

        void ExecuteRepeatBarcodeCheckBoxCommand(object obj)
        {
            if (obj is bool v1)
            {
                using var mdb = new MDbContext();
                var _param = mdb.MParams.FirstOrDefault(p => p.Name == "IsRepeatBarcode");
                if (_param != null)
                {
                    _param.Value = v1.ToString();
                    mdb.SaveChanges();
                }
                isChanged = true;
            }
        }
        void ExecuteUseMESCheckBoxCommand(object obj)
        {
            if (obj is bool v1)
            {
                using var mdb = new MDbContext();
                var _param = mdb.MParams.FirstOrDefault(p => p.Name == "IsUseMES");
                if (_param != null)
                {
                    _param.Value = v1.ToString();
                    mdb.SaveChanges();
                }
                isChanged = true;
            }
        }
        void ExecuteRightCameraCheckBoxCommand(object obj)
        {
            if (obj is bool v1)
            {
                using var mdb = new MDbContext();
                var _param = mdb.MParams.FirstOrDefault(p => p.Name == "IsUseRightCamera");
                if (_param != null)
                {
                    _param.Value = v1.ToString();
                    mdb.SaveChanges();
                }
                isChanged = true;
            }
        }
        void ExecuteLeftCameraCheckBoxCommand(object obj)
        {
            if (obj is bool v1)
            {
                using var mdb = new MDbContext();
                var _param = mdb.MParams.FirstOrDefault(p => p.Name == "IsUseLeftCamera");
                if (_param != null)
                {
                    _param.Value = v1.ToString();
                    mdb.SaveChanges();
                }
                isChanged = true;
            }
        }

        void ExecuteOpenDirectoryCommand()
        {
            using (var fbd = new FolderBrowserDialog())
            {
                System.Windows.Forms.DialogResult result = fbd.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
                {
                    using var mdb = new MDbContext();
                    var _param = mdb.MParams.FirstOrDefault(p => p.Name == "ImagePath");
                    if (_param != null)
                    {
                        _param.Value = ImagePath = fbd.SelectedPath;
                        mdb.SaveChanges();
                    }
                    isChanged = true;
                }
            }
        }
        void ExecuteTextBoxLostFocusCommand(object obj)
        {
            if (obj is string str)
            {
                isChanged = true;
                switch (str)
                {
                    case "LeftCameraIP":
                        {
                            using var mdb = new MDbContext();
                            var _param = mdb.MParams.FirstOrDefault(p => p.Name == "LeftCameraIP");
                            if (_param != null)
                            {
                                _param.Value = LeftCameraIP;
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "RightCameraIP":
                        {
                            using var mdb = new MDbContext();
                            var _param = mdb.MParams.FirstOrDefault(p => p.Name == "RightCameraIP");
                            if (_param != null)
                            {
                                _param.Value = RightCameraIP;
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "ListenerIp":
                        {
                            using var mdb = new MDbContext();
                            var _param = mdb.MParams.FirstOrDefault(p => p.Name == "ListenerIp");
                            if (_param != null)
                            {
                                _param.Value = ListenerIp;
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "PLCIp":
                        {
                            using var mdb = new MDbContext();
                            var _param = mdb.MParams.FirstOrDefault(p => p.Name == "PLCIp");
                            if (_param != null)
                            {
                                _param.Value = PLCIp;
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "ScanCOM":
                        {
                            using var mdb = new MDbContext();
                            var _param = mdb.MParams.FirstOrDefault(p => p.Name == "ScanCOM");
                            if (_param != null)
                            {
                                _param.Value = ScanCOM;
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "BarLimit":
                        {
                            using var mdb = new MDbContext();
                            var _param = mdb.MParams.FirstOrDefault(p => p.Name == "BarLimit" && p.PartNum == partNum);
                            if (_param != null)
                            {
                                _param.Value = BarLimit.ToString();
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    case "RepeatBarcode":
                        {
                            using var mdb = new MDbContext();
                            var _param = mdb.MParams.FirstOrDefault(p => p.Name == "RepeatBarcode");
                            if (_param != null)
                            {
                                _param.Value = RepeatBarcode.ToString();
                                mdb.SaveChanges();
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        #endregion
        #region 导航
        public override void OnDialogClosed()
        {
            if (isChanged)
            {
                aggregator.SendMessage("ReloadParam", "Run");
            }
        }
        public override void OnDialogOpened(IDialogParameters parameters)
        {
            partNum = parameters.GetValue<string>("PartNum");
            if (partNum == null)
            {
                Task.Run(() =>
                {
                    //System.Threading.Thread.Sleep(100);
                    System.Windows.Application.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        OnRequestClose(new Prism.Services.Dialogs.DialogResult(ButtonResult.Cancel));
                    }));
                });
                return;
            }
            LoadParam();
        }
        #endregion
        #region 构造函数
        public ParameterDialogViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            Title = "参数";
            aggregator.ResgiterMessage(arg =>
            {
                string[] strs = arg.Message.Split(new char[] { ';' });
                switch (strs[0])
                {
                    case "PartNumChanged":
                        {
                            partNum = strs[1];
                            LoadParam();
                        }
                        break;
                    default:
                        break;
                }
            }, "Run");
        }
        #endregion
        #region 功能函数
        void LoadParam()
        {
            using var mdb = new MDbContext();
            var _param = mdb.MParams.FirstOrDefault(p => p.Name == "LeftCameraIP");
            if (_param != null)
            {
                LeftCameraIP = _param.Value;
            }
            else
            {
                LeftCameraIP = "192.168.200.100";
                mdb.MParams.Add(new MParam {
                    Name = "LeftCameraIP",
                    Value = LeftCameraIP
                });
                mdb.SaveChanges();
            }
            _param = mdb.MParams.FirstOrDefault(p => p.Name == "RightCameraIP");
            if (_param != null)
            {
                RightCameraIP = _param.Value;
            }
            else
            {
                RightCameraIP = "192.168.201.100";
                mdb.MParams.Add(new MParam
                {
                    Name = "RightCameraIP",
                    Value = RightCameraIP
                });
                mdb.SaveChanges();
            }
            _param = mdb.MParams.FirstOrDefault(p => p.Name == "ListenerIp");
            if (_param != null)
            {
                ListenerIp = _param.Value;
            }
            else
            {
                ListenerIp = "192.168.1.25";
                mdb.MParams.Add(new MParam
                {
                    Name = "ListenerIp",
                    Value = ListenerIp
                });
                mdb.SaveChanges();
            }
            _param = mdb.MParams.FirstOrDefault(p => p.Name == "PLCIp");
            if (_param != null)
            {
                PLCIp = _param.Value;
            }
            else
            {
                PLCIp = "192.168.1.10";
                mdb.MParams.Add(new MParam
                {
                    Name = "PLCIp",
                    Value = PLCIp
                });
                mdb.SaveChanges();
            }
            _param = mdb.MParams.FirstOrDefault(p => p.Name == "ImagePath");
            if (_param != null)
            {
                ImagePath = _param.Value;
            }
            else
            {
                ImagePath = "F:\\Images";
                mdb.MParams.Add(new MParam
                {
                    Name = "ImagePath",
                    Value = ImagePath
                });
                mdb.SaveChanges();
            }
            _param = mdb.MParams.FirstOrDefault(p => p.Name == "ScanCOM");
            if (_param != null)
            {
                ScanCOM = _param.Value;
            }
            else
            {
                ScanCOM = "COM8";
                mdb.MParams.Add(new MParam
                {
                    Name = "ScanCOM",
                    Value = ScanCOM
                });
                mdb.SaveChanges();
            }
            _param = mdb.MParams.FirstOrDefault(p => p.Name == "BarLimit" && p.PartNum == partNum);
            if (_param != null)
            {
                var r = int.TryParse(_param.Value, out var _result);
                if (r)
                {
                    BarLimit = _result;
                }
            }
            else
            {
                BarLimit = 3;
                mdb.MParams.Add(new MParam
                {
                    Name = "BarLimit",
                    Value = BarLimit.ToString(),
                    PartNum = partNum
                });
                mdb.SaveChanges();
            }
            _param = mdb.MParams.FirstOrDefault(p => p.Name == "IsUseMES");
            if (_param != null)
            {
                var r = bool.TryParse(_param.Value, out var _result);
                if (r)
                {
                    IsUseMES = _result;
                }
            }
            else
            {
                IsUseMES = true;
                mdb.MParams.Add(new MParam
                {
                    Name = "IsUseMES",
                    Value = IsUseMES.ToString()
                });
                mdb.SaveChanges();
            }
            _param = mdb.MParams.FirstOrDefault(p => p.Name == "RepeatBarcode");
            if (_param != null)
            {
                RepeatBarcode = _param.Value;
            }
            else
            {
                RepeatBarcode = "888888888";
                mdb.MParams.Add(new MParam
                {
                    Name = "RepeatBarcode",
                    Value = RepeatBarcode
                });
                mdb.SaveChanges();
            }
            _param = mdb.MParams.FirstOrDefault(p => p.Name == "IsRepeatBarcode");
            if (_param != null)
            {
                var r = bool.TryParse(_param.Value, out var _result);
                if (r)
                {
                    IsRepeatBarcode = _result;
                }
            }
            else
            {
                IsRepeatBarcode = false;
                mdb.MParams.Add(new MParam
                {
                    Name = "IsRepeatBarcode",
                    Value = IsRepeatBarcode.ToString()
                });
                mdb.SaveChanges();
            }
        }
        #endregion
    }
}
